


const state = {
    ruleStatus:false,
    couponStatus:false,
    subsidyStatus:false,
    code:null,
    modelCode:null,
    coupon:null,
}

// 倒计时
function startCountdown(){
    let spans = document.getElementsByClassName("fmu-countdown-unit");
    let bannerfixedTop = document.getElementsByClassName("fixed-top-fmu-countdown-unit");
    let subsidyfmu = document.getElementsByClassName("subsidyfmu-countdown-unit");
    let endTime= new Date(new Date().getTime()+1000*60*60*2);//未来时间
    let timer = null;
    clearInterval(timer);
    timer = setInterval(function(){
        //现在时间
        let nowTime = new Date();
        //剩余时间=未来时间-现在时间（未来时间距离现在的秒数）
        let lastTime = parseInt((endTime-nowTime)/1000);
        if( lastTime >= 0 ){
            //换算成天数，一天有86400秒
            let day=parseInt( lastTime / 60 / 60 / 24 );
            //余数代表剩下的小时
            let hour=parseInt( lastTime / 60 / 60 % 24 );
            //代表分钟
            let min=parseInt( lastTime / 60 % 60);
            //代表秒数
            let sec=parseInt( lastTime % 60 );
            //给不足10的数前面添加一个0
            if(day < 10){ 
                 day="0"+day; 
            } 
            if(hour < 10){ 
                hour ="0"+hour; 
            } 
            if(min < 10){ 
                min ="0"+min; 
            } 
            if(sec < 10){
                sec="0" + sec; 
            } 
            // console.log(day,hour, min, sec)
            // console.log('bannerfixedTop',bannerfixedTop)
            spans[0].innerHTML=hour;
            spans[1].innerHTML=min;
            spans[2].innerHTML=sec;

            bannerfixedTop[0].innerHTML=hour;
            bannerfixedTop[1].innerHTML=min;
            bannerfixedTop[2].innerHTML=sec;

            subsidyfmu[0].innerHTML=hour;
            subsidyfmu[1].innerHTML=min;
            subsidyfmu[2].innerHTML=sec;
        }else{
            clearInterval(timer);//清除时间
        }
    },1000);
}
function startMockNumSwitch(){
    let [ mockNumDom ] =  document.getElementsByClassName("mock—num");
    let [ fixedTopMockNumDom ] =  document.getElementsByClassName("fixed-top-mock-num");
    let [ subsidyMockNumDom ] =  document.getElementsByClassName("subsidymock-num");
    let timer = null;
    let num = 0;
    clearInterval(timer);
    timer = setInterval(function(){
        if(num == 9) return num = 0;
        ++ num
        mockNumDom.innerText = num;
        fixedTopMockNumDom.innerText = num;
        subsidyMockNumDom.innerText = num;
    },100)
}
function debounce(fn,wait, target){
    let timeid;
    return function(){
      target()
      if(timeid){
         clearTimeout(timeid)
      }
      timeid = setTimeout(fn,wait)
    }  
  } 
function startBodyScroll(){
    let [ fixedTop ] = document.getElementsByClassName('fixed-top');
    document.body.onscroll = debounce(function(e){
        let bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        // 判断是否到底
        if(scrollHeight - (bodyHeight + scrollTop) < 60){
            getGoodsPager()
        }
    },300,() =>{
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        let backToTopEl = document.getElementsByClassName('backToTop')[0];
        backToTopEl.style.display = "none";
        if( scrollTop > 80 ){
            fixedTop.classList.add("down");
        }else{
            fixedTop.classList.remove("down");
        }
        if( scrollTop > 300 ){
            backToTopEl.style.display = "flex";
        }
    })
}
function ruleClick(){
    let [el] = document.querySelectorAll('.rule-dialog');
    el.style.display = state.ruleStatus === false ? 'flex' : 'none'
    state.ruleStatus = !state.ruleStatus
}
function couponClick(e){
    let [el] = document.querySelectorAll('.coupon-dialog');
        el.style.display = state.couponStatus === false ? 'flex' : 'none'
        state.couponStatus = !state.couponStatus;
    // if( e && e.path[0].id === "goods-wrap" ) return;
    // if(e){
    //     let el = e.path[1]
    //     const _index = el.getAttribute("data-index");
    //     _index && el.classList.add("goods-item-get");
    // }
    // let [el] = document.querySelectorAll('.coupon-dialog');
    // el.style.display = state.couponStatus === false ? 'flex' : 'none'
    // state.couponStatus = !state.couponStatus;
}
function navClick(e){
    let type = e.target.getAttribute('data-type');
    let curNavList = document.getElementsByClassName('nav-adsorption')[0].getElementsByTagName('li');
    let navfixedList = document.getElementsByClassName('list-tab-fixed')[0].getElementsByTagName('li');
    Array.from(curNavList).forEach( (el, index) =>{  
        el.classList.remove("active"); 
        navfixedList[index].classList.remove("active"); 
    })
    curNavList[type].classList.add("active")
    navfixedList[type].classList.add("active")
    pager.params = {
        pageSize: 20,
        pageNum: 1,
        type
    }
    backToTop()
    pager.isBreak = false;
    getGoodsPager();
}
function copyContent(){
    const $textarea = document.createElement('textarea');
    $textarea.readOnly = 'readonly';
    $textarea.style = {
        position:'absolute',
        left:'-9999px'
    }
    $textarea.value = state.modelCode;
    document.body.appendChild($textarea);
    $textarea.select();
    document.execCommand('Copy');
    document.body.removeChild($textarea);
}
function subsidyMarkClick(e){
    let [el] = document.querySelectorAll('.subsidy-dialog');
    el.style.display = state.subsidyStatus === false ? 'flex' : 'none'
    state.subsidyStatus = !state.subsidyStatus
}
function backToTop() {
    document.body.scrollIntoView({
        behavior:"smooth"
    })
}
function initDomClick(){
    let rule = [
        {
            className:'banner-rule',
            events:ruleClick
        },
        {
            className:'rule-dialog-del',
            events:ruleClick
        },
        {
            className:'coupon-dialog-del',
            events:couponClick
        },
        // {
        //     className:'goods-wrap',
        //     events:couponClick
        // },
        {
            className:'nav-adsorption',
            events:navClick
        },
        {
            className:'list-tab-fixed',
            events:navClick
        },
        {
            className:'close-subsidy',
            events:subsidyMarkClick
        },
        {
            className:'receive',
            events:subsidyMarkClick
        },
        {
            className:'open-btn',
            events:function(e){
                copyContent();
                tips()
                couponClick()
            }
        },
        {
            className:'backToTop',
            events:backToTop
        }
    ]
    for(let i=0; i<rule.length; i++){
        const { className, events } = rule[i];
        let [ el ] = document.querySelectorAll(`.${className}`)
        if(el) el.onclick = events;
    }
}
function initPageData(){
    // 进入页面显示购物补贴弹窗
    subsidyMarkClick()
}
function startNumberScroll(){
    const [ el ] = document.getElementsByClassName('scroll-num');
    el.style.transform = `translateY(-20%)`;
}
function goodsClickInit(){
  let goodsList = document.querySelectorAll(`.goods-item`);
  Array.from(goodsList).forEach( els =>{
    els.onclick = function(){
        els.classList.add("goods-item-get");
        state.code = els.getAttribute('data-code');
        state.modelCode = els.getAttribute('data-modelCode');
        state.coupon = els.getAttribute('data-coupon');
        document.getElementsByClassName("coupon-result")[0].innerText = `优惠口令${state.code}`
        document.getElementById("data-coupon").innerText = `${state.coupon}`;
        couponClick()
    }
  })
}
// 开启倒计时
startCountdown()
// 开启数字切换效果
startMockNumSwitch()
// 开启滚动条事件
startBodyScroll()
// 开启数字滚动效果
startNumberScroll()
// 初始化事件绑定
initDomClick()
// 初始化页面配置
initPageData()


/**
 * 分页数据请求
 */
var pager = {
  // 分页请求参数
  params: {
    pageSize: 20,
    pageNum: 1,
    type: 0
  },
  // 是否到底了
  isBreak: false,
  // 是否在等待中（防止重复请求发生）
  pending: false,
}
/**
 * 获取商品分页
 */
function getGoodsPager() {
  // 是否加载完/请求锁
  if (pager.isBreak && pager.pending) return;
  // 开始请求
  $.ajax({
    type: 'GET',
    url: 'http://lddapi.haokan88.cn/api/product/items',
    data: pager.params,
    dataType: 'json',
    beforeSend: function() {
      pager.pending = true;
    },
    success: function(response){
      response.data = response.data || []
      // mock数据
      for (let index = 0; index < response.data.length; index++) {
        var price_integer = response.data[index].item_price.split('.')[0];
        var price_decimal = response.data[index].item_price.split('.')[1];
        response.data[index].price_integer =  price_integer;
        response.data[index].price_decimal =  price_decimal ? '.' + price_decimal : '';
      }
      var html = '';
      response.data.forEach(function(goods, index) {
        html += `<div class="goods-item" data-index="${index}" data-coupon="${goods.coupon_amount_text}" data-modelCode="${goods.model}" data-code="${ goods.passwordSimple }">`;
        html += '<p class="item-img">';
        html += pager.params.pageNum == 1 && index < 10 ? '<span class="item-' + (index + 1 > 3 ? 3 : index + 1) + '">Top' + (index + 1) + '</span>' : '';
        html += '<img class="w100" src="' + goods.pict_url + '" />';
        html += '</p>';
        html += '<div class="item-info">';
        html += '<p class="item-title">' + goods.title + '</p>';
        html += '<div class="item-desc">';
        html += '<p class="item-price bold">';
        html += '<em>补贴价</em><span class="integer"><small>¥</small>' + goods.price_integer + '</span><span class="decimal">' + goods.price_decimal + '</span>';
        html += '</p>';
        html += '<p class="item-sale">' + goods.ori_item_price + '</p>';
        html += '</div>';
        html += '<p class="item-btn">';
        html += '<span class="discount">' + goods.tagdiscount + '折</span>';
        html += '<span class="coupon">优惠券￥' + goods.coupon_amount_text + '</span>';
        html += '</p>';
        html += '</div>';
        html += '</div>';
      })
      if (pager.params.pageNum === 1 ) {
        $("#goods-wrap").empty()
      }
      // 处理分页
      pager.pending = false;
      pager.params.pageNum += 1;
      // 判断是否加载完
      if (response.data.length < pager.params.pageSize) {
        pager.isBreak = true;
      }
      $("#goods-wrap").append(html)
      goodsClickInit()
    },
    error: function(){
      pager.pending = false;
    }
  })
}
getGoodsPager()

